<?php
class uplogModel extends Model{
	public $primaryKey='id';
	public $table='uplog';
	public $remote_obj;
	
	public function __construct(){
		parent::__construct();
		
		$this->_auto = array();
		$this->_valid = array(
		
	
		
		);
		$this->_valid_for_add = array();
		$this->_valid_for_mod = array();
		$this->_valid_for_select = array();
		
		$this->remote_obj=new upload_remote();
		
	}
	
	public function save_remote($set,$content, $ext = 'jpg|jpeg|gif|png', $self = 0) {
		if(!$content) return $content;
		if(!preg_match_all("/src=([\"|']?)([^ \"'>]+\.($ext))\\1/i", $content, $matches)) return $content;
		
		$urls = $oldpath = $newpath = array();
		foreach($matches[2] as $k=>$url) {
			if(in_array($url, $urls)) continue;
			$urls[$url] = $url;		
			if(strpos($url, '://') === false) continue;
			if(!$self) {
				if(VG::$config['cookie_domain']) {
					if(strpos($url, VG::$config['cookie_domain'].'/') !== false) continue;
				} else {
					if(strpos($url, VG::$config['base_url']) !== false) continue;
				}
			}
			$filedir = 'common/uploads/'.date('Y/m/d').'/';
			$filepath = VG::$config['base_url'].$filedir;
			$fileroot = './'.$filedir;
			$file_ext = pathinfo($url,PATHINFO_EXTENSION);
			$filename = time().rand(1000,9999).'.'.$file_ext;
			$newfile = $fileroot.$filename;
			mkdir($fileroot,0777,true);
			if(copy($url, $newfile)) {
				if(preg_match("/^(jpg|jpeg|gif|png)$/i", $file_ext)) {
					if(!getimagesize($newfile)) {
						unlink($newfile);
						continue;
					}
					
				}
				$oldpath[] = $url;
				$newurl = $filepath.$filename;
				
				$newpath[] = $newurl;
			}
		}
		unset($matches);
		
		//uplog
		$ctl=& VG::get_instance();
		//id  uniq	moduleid	controller	tb	itemid	fileurl	addtime	userid
		foreach($newpath as $k=>$v){
			$data=array_merge($set,array('moduleid'=>$ctl->moduleid,'controller'=>isset($ctl->control)?$ctl->control:VG::$control,'fileurl'=>$newfile,'addtime'=>time(),'userid'=>$ctl->userid));
			
			
			if($data['uniq'] && $data['moduleid'] && $data['controller'] && $data['tb']){
				
				$data['fileurl']=$this->remote_obj->add(trim($data['fileurl'],'./'));//远程ftp
				
				$r=$this->field('id')->where(array('moduleid'=>$ctl->moduleid,'controller'=>isset($ctl->control)?$ctl->control:VG::$control,'tb'=>$data['tb'],'itemid'=>$data['itemid'],'fileurl'=>$data['fileurl'],'userid'=>$ctl->userid))->easy_find();
				if(!$r){
					$this->easy_insert($data,0,false,false);
				}
			}
		}
		
		return str_replace($oldpath, $newpath, $content);
	}
	//保存base64图片
	public function save_local($set,$content) {
		if($content == '<br type="_moz" />') return '';//FireFox
		if($content == '&nbsp;') return '';//Chrome
		$content = preg_replace("/allowScriptAccess=\"always\"/i", "", $content);
		$content = preg_replace("/allowScriptAccess/i", "allowscr-iptaccess", $content);
		if(!preg_match_all("/src=([\"|']?)([^ \"'>]+)\\1/i", $content, $matches)) return $content;
		foreach($matches[2] as $k=>$url) {
			if(is_crsf($url)) $content = str_replace($url, '/common/images/nopic.gif', $content);
		}
		if(strpos($content, 'data:image') === false) return $content;
		
		$urls = $oldpath = $newpath = array();
		
		foreach($matches[2] as $k=>$url) {
			if(in_array($url, $urls)) continue;
			$urls[$url] = $url;
			if(strpos($url, 'data:image') === false) continue;
			if(strpos($url, ';base64,') === false) continue;
			$t1 = explode(';base64,', $url);
			$t2 = explode('/', $t1[0]);
			$file_ext = $t2[1];
			in_array($file_ext, array('jpg', 'gif', 'png')) or $file_ext = 'jpg';
			
			$filedir = 'common/uploads/'.date('Y/m/d').'/';
			$filepath = VG::$config['base_url'].$filedir;
			$fileroot = './'.$filedir;
			$filename = time().rand(1000,9999).'.'.$file_ext;
			$newfile = $fileroot.$filename;
			if(!preg_match("/^(jpg|jpeg|gif|png)$/i", $file_ext)) continue;
			mkdir($fileroot,0777,true);
			
			if(file_put_contents($newfile, base64_decode($t1[1], 0))) {
				if(!@getimagesize($newfile)) {
					unlink($newfile);
					continue;
				}
				$oldpath[] = $url;
				$newurl = $filepath.$filename;
				
				$newpath[] = $newurl;
			}
		}
		
		//uplog
		$ctl=& VG::get_instance();
		//id  uniq	moduleid	controller	tb	itemid	fileurl	addtime	userid
		foreach($newpath as $k=>$v){
			$data=array_merge($set,array('moduleid'=>$ctl->moduleid,'controller'=>isset($ctl->control)?$ctl->control:VG::$control,'fileurl'=>$newfile,'addtime'=>time(),'userid'=>$ctl->userid));
			
			
			if($data['uniq'] && $data['moduleid'] && $data['controller'] && $data['tb']){
				
				$data['fileurl']=$this->remote_obj->add(trim($data['fileurl'],'./'));//远程ftp
				
				$r=$this->field('id')->where(array('moduleid'=>$ctl->moduleid,'controller'=>isset($ctl->control)?$ctl->control:VG::$control,'tb'=>$data['tb'],'itemid'=>$data['itemid'],'fileurl'=>$data['fileurl'],'userid'=>$ctl->userid))->easy_find();
				if(!$r){
					$this->easy_insert($data,0,false,false);
				}
			}
		}
		
		unset($matches);
		return str_replace($oldpath, $newpath, $content);
	}

	
	public function add($data=array()){
        $data=array_merge($data,VG::$gp_var); 
		
        
        if($data['uniq'] && $data['moduleid'] && $data['controller'] && $data['fileurl'] && $data['tb']){
        
            $ctl=& VG::get_instance();
            $data=array_merge($data,array('addtime'=>time(),'userid'=>$ctl->userid));
			
			
			$data['fileurl']=$this->remote_obj->add(trim($data['fileurl'],'./'));//远程ftp
			
            $itemid=$this->easy_insert($data);
			
            return array($itemid,$data['fileurl']);
        }else{
            return array(0,'');
        }
	}
    public function ok($uniq,$itemid){
        if($uniq && $itemid){
            return $this->where(array('uniq'=>$uniq))->easy_update(array('itemid'=>$itemid));
        }
        return false;
    }
	public function clear($moduleid,$controller,$tb,$itemid){
         $arr=$this->field('id,fileurl')->where(array('moduleid'=>$moduleid,'controller'=>$controller,'tb'=>$tb,'itemid'=>$itemid))->easy_select();
        foreach($arr as $k=>$v){
            
			if(VG::$config['ftp_remote'] && VG::$config['remote_url']){
				$this->remote_obj->del($v['fileurl']);
			}else{
				if(file_exists($v['fileurl']) && (strpos($v['fileurl'],'..')===false) ){
					unlink($v['fileurl']);
				}
			}
		
            $this->easy_delete($v['id']);
        }
	}
    public function garbage(){
        $start=strtotime(date('Y-m-d'))-7*3600*24;
        $arr=$this->field('id,fileurl')->where(array('itemid'=>'0','addtime <='=>$start))->limit('100')->easy_select();
        foreach($arr as $k=>$v){
			if(VG::$config['ftp_remote'] && VG::$config['remote_url']){
				$this->remote_obj->del($v['fileurl']);
			}else{
				if(file_exists($v['fileurl']) && (strpos($v['fileurl'],'..')===false) ){
					unlink($v['fileurl']);
				}
			}
			
            $this->easy_delete($v['id']);
        }
    }
	


}